import { createStore, createLogger } from "vuex";
import axios from "axios";

export interface RootState {
  list: ListItemState[];
  car: CarItemState[];
}

export interface ListItemState {
  title: string;
  desc: string;
  price: number;
  id: string;
  url: string;
}

export interface CarItemState extends ListItemState {
  count: number;
  isChecked: boolean;
}

const store = createStore<RootState>({
  state: {
    list: [],
    car: JSON.parse(localStorage.getItem("car") || "[]"),
  },
  getters: {
    detail(state) {
      return (id: string) => {
        return state.list.find((v) => v.id === id);
      };
    },
    // 总数量 总价钱
    allPrice(state) {
      return state.car.reduce((p, n) => {
        return n.isChecked ? p + n.count * n.price : p;
      }, 0);
    },
    allCount(state) {
      return state.car.reduce((p, n) => {
        return n.isChecked ? p + n.count : p;
      }, 0);
    },
    allCountNoCheck(state) {
      return state.car.reduce((p, n) => {
        return p + n.count;
      }, 0) || '';
    },
  },
  mutations: {
    setList(state, payload: ListItemState[]) {
      state.list = payload;
    },
    addCar(state, payload: ListItemState) {
      const item = state.car.find((v) => v.id === payload.id);
      if (item) {
        item.count++;
      } else {
        state.car.unshift({
          ...payload,
          count: 1,
          isChecked: false,
        });
      }
    },
    addCarItemCount(state, payload: string) {
      const item = state.car.find((v) => v.id === payload);
      item && item.count++;
    },
    subCarItemCount(state, payload: string) {
      const item = state.car.find((v) => v.id === payload);
      item && item.count--;
    },
    switchCheck(state, payload: string) {
      const item = state.car.find((v) => v.id === payload);
      if (item) {
        item.isChecked = !item.isChecked;
      }
    },
    switchAllCheck(state, payload: boolean) {
      state.car.forEach((v) => (v.isChecked = payload));
    },
    deleteCheckedCarItem(state) {
      state.car = state.car.filter(v => !v.isChecked)
    },
    deleteByIDCarItem(state, payload: string) {
      state.car = state.car.filter(v => v.id !== payload)
    }
  },
  actions: {
    async fetchList(context) {
      const resp = await axios.get("/api/list");
      context.commit("setList", resp.data.data);
    },
  },
  modules: {},
  plugins: [createLogger()],
});

store.subscribe((mutation, state) => {
  localStorage.setItem("car", JSON.stringify(state.car));
});

export default store;
